# codding = utf-8
import asyncio
import json

import cv2
import easydict
import websockets

from cjc_tools.cv2_base64 import base64_to_cv2_image

IP_ADDR = "127.0.0.1"
IP_PORT = "9000"

from tools import create_welcome_msg, create_msg_to_server, create_img_request_msg, create_start_trace_msg


# 握手，通过发送hello，接收"123"来进行双方的握手。
async def clientHands(websocket):
    while True:
        await  asyncio.sleep(0)
        response_str = await websocket.recv()
        a = response_str
        e = json.loads(a)
        print(e)
        ea = easydict.EasyDict(e)
        if ea.data is not None and ea.data.track is not None and ea.data.img is not None:
            cv2.imshow("", base64_to_cv2_image(ea.data.img))
            # print(ea.data.track)
            cv2.waitKey(1)


# 向服务器端发送消息
async def clientSend(websocket):
    while True:
        await  asyncio.sleep(0)
        await websocket.send(create_start_trace_msg())
        await websocket.send(create_img_request_msg())


# 进行websocket连接
async def clientRun():
    ipaddress = IP_ADDR + ":" + IP_PORT
    ws = await websockets.connect("ws://" + ipaddress)
    return await asyncio.gather(clientSend(ws),clientHands(ws))



# main function
if __name__ == '__main__':
    print("======client main begin======")
    asyncio.get_event_loop().run_until_complete(clientRun())
